# coding=utf-8
import multiprocessing
import time

import pythoncom
import win32com.client

from docx2pdf import convert

import os


def get_all_files_in_directory(directory_path):
    # 初始化一个空列表来存放所有文件的完整路径
    all_files = []
    # os.walk()递归遍历目录树
    for root, dirs, files in os.walk(directory_path):
        for file in files:
            # 使用os.path.join()拼接出文件的完整路径
            full_path = os.path.join(root, file)
            all_files.append(full_path)

    return all_files


def docx_to_pdf(docx_path,pdf_path):
    try:
        pythoncom.CoInitialize()
        convert(docx_path, pdf_path)
        print(f"{docx_path} 文档转为pdf成功")
        time.sleep(0.1)
    except Exception as e:
        print(f"{docx_path} 文档转为pdf失败",e)
    finally:
        pythoncom.CoUninitialize()  # 清理COM环境


def docx_to_pdf_bywin32(docx_path, pdf_path):
    try:
        pythoncom.CoInitialize()
        # word = win32com.client.Dispatch("Word.Application")
        word = win32com.client.DispatchEx("Word.Application")

        # 打开DOCX文件并保存为PDF
        doc = word.Documents.Open(docx_path)
        doc.SaveAs(pdf_path, FileFormat=17)  # 17 表示PDF格式
        doc.Close()

        # 关闭Word应用程序
        word.Quit()
        time.sleep(0.1)

        print(f"{docx_path} 文档转为pdf成功")
    except Exception as e:
        print(f"{docx_path} 文档转为pdf失败: {e}")
    finally:
        pythoncom.CoUninitialize()  # 清理COM环境

if __name__ == '__main__':
    # # # 调用函数并传入文件夹路径
    # directory_path = r'D:\python\hgws\threads\docx'  # 更改为你的文件夹路径
    # s = time.time()
    # file_paths = get_all_files_in_directory(directory_path)
    # for file in file_paths:
    #     pdf_file = file.replace("docx\\","pdf\\")
    #     pdf_file = pdf_file.replace("docx","pdf")
    #     print(pdf_file)
    #     # docx_to_pdf(file,pdf_file)
    #     docx_to_pdf_bywin32(file,pdf_file)    # 39
    # e = time.time()
    # print("多进程执行时间：",e-s)

    directory_path = r'D:\python\hgws\threads\docx'  # 更改为你的文件夹路径
    docx_files = get_all_files_in_directory(directory_path)
    pdf_files = []
    for file in docx_files:
        pdf_file = file.replace("docx\\","pdf\\")
        pdf_file = pdf_file.replace("docx","pdf")
        pdf_files.append(pdf_file)

    s = time.time()
    with multiprocessing.Pool(processes=4) as pool:
        # 将转换任务提交给进程池
        results = [pool.apply_async(docx_to_pdf_bywin32, args=(docx_files[i], pdf_files[i])) for i  in range(len(docx_files))]

        # 等待所有任务完成
        for result in results:
            result.get()
    e = time.time()
    print("多进程执行时间：",e-s)